package xyz.robinbingo.pfboot.entity.lazymodel;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import xyz.robinbingo.pfboot.entity.Car;
import xyz.robinbingo.pfboot.repository.CarRepository;

import java.util.List;
import java.util.Map;

/**
 * LazyModelCar
 *
 * @author Robin
 * @date 2018/10/18 13:46
 **/
@Component
public class LazyModelCar extends LazyDataModel<Car> {

    private static final long serialVersionUID = 8085169542695014923L;

    @Autowired
    private CarRepository carRepository;

    @Override
    public List<Car> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {

        Sort sort = null;

        if (StrUtil.isNotBlank(sortField)) {
            Sort.Direction direction = null;
            switch (sortOrder) {
                case ASCENDING: {
                    direction = Sort.Direction.ASC;
                    break;
                }
                case DESCENDING: {
                    direction = Sort.Direction.DESC;
                }
                default:
                    break;
            }
            sort = new Sort(direction, sortField);
        }
        int page = first / pageSize;
        PageRequest pageRequest = sort == null ? PageRequest.of(page, pageSize) : PageRequest.of(page, pageSize, sort);
        Page<Car> carPage;
        Car car = new Car();
        BeanUtil.copyProperties(filters, car);
        carPage = carRepository.findAll(Example.of(car), pageRequest);
        setRowCount((int) carPage.getTotalElements());
        return carPage.getContent();
    }

    @Override
    public Car getRowData(String rowKey) {
        return carRepository.findById(Integer.valueOf(rowKey)).orElse(null);
    }

    @Override
    public Object getRowKey(Car car) {
        return car.getId();
    }
}
